/*
 *    Copyright 2009-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.reflection.property;

import java.util.Iterator;

/**
 * 属性的分词器, 支持迭代器的方式访问
 * 举个例子，在访问 "order[0].item[0].name" 时，
 * 我们希望拆分成 "order[0]"、"item[0]"、"name" 三段，
 * 那么就可以通过 PropertyTokenizer 来实现。
 *
 * @author Clinton Begin
 */
public class PropertyTokenizer implements Iterator<PropertyTokenizer> {

  /**
   * 当前字符串(索引名)
   * 如 order[0], {@link this#getIndexedName()}就等于 order
   */
  private String name;

  /**
   * 索引名+索引
   */
  private final String indexedName;

  /**
   * 索引(索引值)
   * 如 order[0], {@link this#getIndex()}就等于 0
   */
  private String index;

  /**
   * 剩余字符串
   */
  private final String children;

  public PropertyTokenizer(String fullname) {

    // .分割
    // 获取首次出现.的索引值
    int delim = fullname.indexOf('.');
    if (delim > -1) {

      // 根据.分割出当前字符串与剩余字符串
      name = fullname.substring(0, delim);
      children = fullname.substring(delim + 1);
    } else {
      // 没有.
      // 当前字符串就是传入的字符串
      // 剩余字符串为null
      name = fullname;
      children = null;
    }

    // 赋值
    indexedName = name;

    // 如果当前索引存在 [
    // 就认为存在索引值
    delim = name.indexOf('[');
    if (delim > -1) {

      // 拿到索引值
      // 正常情况下获取的值就是 [index]中的 index 值
      index = name.substring(delim + 1, name.length() - 1);

      // 拿到索引名
      name = name.substring(0, delim);
    }
  }

  public String getName() {
    return name;
  }

  public String getIndex() {
    return index;
  }

  public String getIndexedName() {
    return indexedName;
  }

  public String getChildren() {
    return children;
  }

  @Override
  public boolean hasNext() {
    return children != null;
  }

  @Override
  public PropertyTokenizer next() {
    // 用剩余字符串再进行分词
    return new PropertyTokenizer(children);
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException("Remove is not supported, as it has no meaning in the context of properties.");
  }
}
